/*
 * HttpHamdler.Java
 */
package org.puresilk.android.net;

import org.puresilk.android.util.Logger;

import android.os.Handler;
import android.os.Message;

/**
 * Abstract class to extend for managing
 * a WorxRPC call.  
 * 
 * @author david
 *
 */
public abstract class HttpHandler extends Handler implements HttpCaller {
	private static final Logger logger = Logger.getInstance();
	/**
	 * HttpResponse Message Queue 
	 */
	public void handleMessage(Message msg){
		//logger.debug("Msg Handler:" + String.valueOf(msg.what));

		// what kind of message did we get?
		switch(msg.what) {
		
			// Process error notifications
			case HttpResponse.PARSING_ERROR:
			case HttpResponse.JSON_PARSING_ERROR:
			case HttpResponse.READING_ERROR:
				onResponseError((HttpException)msg.obj);
				break;
				
			// Process progress notifications
			case HttpResponse.PROGRESS_UPDATE:
				onResponseProgress((String)msg.obj);
				break;
			
			// Process progress notifications
			case HttpResponse.WRITE_UPDATE:
				onWriteProgress(Integer.parseInt((String)msg.obj));
				break;
				
			// new request about to happen
			case HttpResponse.NEW:
				onRequestStart();
				break;
				
			// Data is ready for processing
			case HttpResponse.DATA_READY:
				onResponseReady((HttpResponse)msg.obj);
				break;
				
			// The rest...
			default:
				// don't know the message
				logger.warn("Unknown Message ID: " + String.valueOf(msg.what));
		}	
	}

	//----------------------------------------
	// Abstract HttpCaller Implementation 
	// for overriding in descendant classes
	//----------------------------------------
	/**
	 * React to a new rpc call
	 */
	public abstract void onRequestStart();
	/** 
	 * Report on progress
	 */
	public abstract void onResponseProgress(String msg);
	/**
	 * Report on write update 
	 */
	public abstract void onWriteProgress(int bytesWritten);
	/**
	 * Response is ready to process
	 */
	public abstract void onResponseReady(HttpResponse rsp);
	/**
	 * Report an error 
	 */
	public abstract void onResponseError(HttpException hx);
}
